//
//  WeiboHomeTableViewController.swift
//  SinaWeibo
//
//  Created by 风不会停息 on 2016/11/12.
//  Copyright © 2016年 风不会停息. All rights reserved.
//

import UIKit

import SVProgressHUD

private let status = "StatusCellID"
private let retweed = "WBRetweetedStatusCellID"

class WeiboHomeViewController: WeiboBaseViewController,UITableViewDelegate,UITableViewDataSource {

    
    let homeViewModel = WBHomeViewModel()
    
    lazy var refresh: WBRefreshControl = WBRefreshControl()
    
    let tableView:UITableView = UITableView(frame: UIScreen.main.bounds, style: .plain)
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(push))
        if !islogin {
            
            self.visitorView.updateVisitorView(title: "关注一些人,关注一些人,回到这里看看有什么惊喜", imageName: "visitordiscover_feed_image_smallicon", isHome: true)
            return
        }
        setUI()
        loadData()
    
    }
    func loadData(){
        
        homeViewModel.loadData(isPullup: indicator.isAnimating) { (isSuccess,count) in
            
            if !isSuccess{
                return
            }
            
            
            if !self.indicator.isAnimating{
                self.startAnimtaion(count: count)
            }
            
            //需要停止菊花转动
            self.refresh.endRefreshing()
            self.indicator.stopAnimating()

            self.tableView.reloadData()
        }
    }
    
    func setUI(){
    
        
        tableView.delegate = self
        
        tableView.dataSource = self
        
        view.addSubview(tableView)
        
//        tableView.register(UITableViewCell.self, forCellReuseIdentifier: sta)
        
        let Statusnib = UINib(nibName: "WBHomeCell", bundle: nil)
        let Retweeted = UINib(nibName: "WBRetweetedStatusCell", bundle: nil)
        tableView.register(Statusnib, forCellReuseIdentifier: status)
        tableView.register(Retweeted, forCellReuseIdentifier: retweed)
//        tableView.rowHeight = 350
        //cell之间的线的格式设置
        tableView.separatorStyle = .none
        tableView.tableFooterView = indicator
        
        
        //直接给refreshControl实例化就可以用
  
//        tableView.refreshControl = refresh
        
        //监听事件类型
//        tableView.refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        
        refresh.addTarget(self, action: #selector(loadData), for: .valueChanged)

        tableView.addSubview(refresh)
        
        
        
        
        //添加tiplabel
        tipLabel.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        //self.view.addSubview(tipLabel)
        //添加导航视图控制器的根视图上
        //设置Y值
        tipLabel.frame.origin.y = navBarHeight - 35
        //self.navigationController?.view.addSubview(tipLabel)
        //移动到导航条下面
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
        
        
    }
    
    //提示显示多少条数据
    private func startAnimtaion(count: Int) {
        //如果正在做动画就直接返回
        if tipLabel.isHidden == false {
            return
        }
        let tipText = count == 0 ? "没有新微博" : "有\(count)条微博"
        //设置文字
        tipLabel.text = tipText
        //1. 在开始动画前显示tipLabel
        self.tipLabel.isHidden = false
        
        //在开始动画之前记录Y值
        let y = self.tipLabel.frame.origin.y
        UIView.animate(withDuration: 1, animations: {
            //2. 做动画 修改Y值
            self.tipLabel.frame.origin.y = navBarHeight
        }, completion:{ (_) -> () in
            //3. 回去的动画  延迟
            UIView.animate(withDuration: 1, delay: 1, options: [], animations: {
                self.tipLabel.frame.origin.y = y
            }, completion: { (_) -> () in
                self.tipLabel.isHidden = true
            })
        })
    }

    
    func push(){
        
        let vc = UIViewController()
        vc.view.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
        
    }
    //指示器
    internal lazy var indicator:UIActivityIndicatorView = {
       let indictor = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
        //开启静默加载的时候转动
//        indictor.startAnimating()
        return indictor
    }()
    //显示加载多少条数据的标签
    private lazy var tipLabel: UILabel = {
        let l = UILabel(title: "", fontSize: 16, textcolor: UIColor.white)
        //设置背景颜色
        l.backgroundColor = UIColor.orange
        //设置隐藏
        l.textAlignment = .center
        l.isHidden = true
        return l
    }()
    

    
 }
extension WeiboHomeViewController{
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.homeViewModel.viewmodelArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let viewmodel = self.homeViewModel.viewmodelArr[indexPath.row]
        let cellID = getCellID(viewmodel: viewmodel)
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! WBHomeCell
        cell.viewmodel = viewmodel
        cell.selectionStyle = .none
        return cell
        
    }
    private func getCellID(viewmodel:WBStatusViewModel)->String{
        
        return viewmodel.status?.retweeted_status == nil ? status : retweed
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //根据cell最底部的空间的y来决定行高
        let model = self.homeViewModel.viewmodelArr[indexPath.row]
        //        let cellID = getCellID(viewmodel: model)
        //
        //        //heightforrow调用了dequeue，，，，dequeue又调用了heightforrow，形成了递归调用，程序会崩溃，所以不能用这个方法来找到cell
        //        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! WBHomeCell
        let cellName = nibName(viewmodel: model)
        
        let cell = UINib(nibName: cellName, bundle: nil).instantiate(withOwner: nil, options: nil).last as! WBHomeCell
        //不设置数据的话，collectionView不会有值，只能是默认的高度。
        //设置数据后，viewmodel会走didset方法

        
        
        cell.viewmodel = model
        cell.layoutIfNeeded()
        //设置数据后，自动布局没有生效
        
        
        return cell.toolBar.frame.maxY
    }
    
    func nibName(viewmodel:WBStatusViewModel) -> String{
        
        return viewmodel.status?.retweeted_status == nil ? "WBHomeCell":"WBRetweetedStatusCell"
    }
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if  indicator.isAnimating == false && indexPath.row == homeViewModel.viewmodelArr.count - 2 {
            //将要展示倒数第二个cell的时候，开始动画
            
            indicator.startAnimating()
//            print("小菊花开始转动啦")
            loadData()
        }
    }
}
